package com.yj.rselasticsearch.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yj.common.annotation.Log;
import com.yj.common.constant.DataConstants;
import com.yj.common.core.controller.BaseController;
import com.yj.common.core.domain.AjaxResult;
import com.yj.common.core.domain.entity.Member;
import com.yj.common.core.domain.entity.WhiteList;
import com.yj.common.enums.BusinessType;
import com.yj.common.utils.FastUtils;
import com.yj.common.utils.bean.BeanUtils;
import com.yj.rselasticsearch.domain.dto.WhiteListDto;
import com.yj.rselasticsearch.domain.vo.WhiteListVo;
import com.yj.rselasticsearch.service.MemberService;
import com.yj.rselasticsearch.service.WhiteListService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 白名单
 *
 * @author luoY
 */
@Api("白名单")
@RestController
@Slf4j
@RequestMapping("whiteList")
public class WhiteListController extends BaseController {

    @Resource
    private WhiteListService whiteListService;

    @Resource
    private MemberService memberService;

    /**
     * 分页查询白名单数据
     *
     * @param whiteListDto
     * @return
     */
    @PreAuthorize("@ss.hasPermi('whiteList:list:query')")
    @ApiOperation("分页查询白名单数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "页码", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "phone", value = "  手机号", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userName", value = "用户姓名", dataType = "String", dataTypeClass = String.class)
    })
    @PostMapping("getWhiteListInfo")
    public AjaxResult getWhitListInfo(@RequestBody WhiteListDto whiteListDto) {
        IPage<WhiteListVo> whiteListIVoPage = new Page<>(whiteListDto.getPageIndex(), whiteListDto.getPageSize());
        IPage<WhiteList> whiteListIPage = new Page<>(whiteListDto.getPageIndex(), whiteListDto.getPageSize());
        whiteListIPage = whiteListService.page(whiteListIPage, new LambdaQueryWrapper<WhiteList>().eq(WhiteList::getStatus, DataConstants.Number.ZERO).
                like(!FastUtils.checkNull(whiteListDto.getPhone()),WhiteList::getPhone,whiteListDto.getPhone()).
                like(!FastUtils.checkNull(whiteListDto.getUserName()),WhiteList::getUserName,whiteListDto.getUserName()).orderByDesc(WhiteList::getCreateTime));
        if (!FastUtils.checkNullOrEmpty(whiteListIPage.getRecords())){
            List<String> phoneList = whiteListIPage.getRecords().stream().map(WhiteList::getPhone).collect(Collectors.toList());
            List<Member> memberList = memberService.list(new LambdaQueryWrapper<Member>().in(Member::getPhone, phoneList));
            whiteListIVoPage.setPages(whiteListIPage.getPages());
            whiteListIVoPage.setTotal(whiteListIPage.getTotal());
            List<WhiteListVo> whiteListVoList = new LinkedList<>();
            if (!FastUtils.checkNullOrEmpty(whiteListIPage.getRecords())){
                whiteListIPage.getRecords().forEach(data -> {
                    WhiteListVo whiteListVo = new WhiteListVo();
                    BeanUtils.copyBeanProp(whiteListVo, data);
                    if (!FastUtils.checkNullOrEmpty(memberList)) {
                        memberList.forEach(m -> {
                            if (data.getPhone().equals(m.getPhone())) {
                                whiteListVo.setMember(m);
                            }
                        });
                        whiteListVoList.add(whiteListVo);
                    }
                });
                whiteListIVoPage.setRecords(whiteListVoList);
            }
        }

        return AjaxResult.success(whiteListIPage);
    }

    /**
     * 新增数据
     *
     * @param whiteList
     * @return
     */
    @PreAuthorize("@ss.hasPermi('whiteList:list:add')")
    @ApiOperation("新增白名单")
    @Log(title = "系统管理-白名单", businessType = BusinessType.INSERT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "用户手机号", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userName", value = "用户姓名", dataType = "String", dataTypeClass = String.class)
    })

    @PutMapping("addWhiteListInfo")
    public AjaxResult addWhiteListInfo(@RequestBody WhiteListDto whiteList) {
        //先校验手机号是否存在
        WhiteList whiteList1 = whiteListService.getOne(new LambdaQueryWrapper<WhiteList>().eq(WhiteList::getPhone,whiteList.getPhone()).eq(WhiteList::getStatus,DataConstants.Number.ZERO));
        if(!FastUtils.checkNull(whiteList1)){
            return AjaxResult.error("添加白名单失败，手机号已存在！");
        }
        Integer result = whiteListService.insertSelective(whiteList);
        if (result > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("添加白名单信息失败！");
    }

    /**
     * 更新白名单信息
     *
     * @param whiteListDto
     * @return
     */
    @PreAuthorize("@ss.hasPermi('whiteList:list:update')")
    @ApiOperation("更新白名单信息")
    @Log(title = "系统管理-白名单", businessType = BusinessType.UPDATE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "数据id", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userName", value = "用户姓名", dataType = "String", dataTypeClass = String.class),
    })
    @PutMapping("updateWhiteListInfo")
    public AjaxResult updateWhiteListInfo(@RequestBody WhiteListDto whiteListDto) {
//        if (FastUtils.checkNull(whiteListDto.getUserName())){
//            return AjaxResult.error("用户名不能为空！");
//        }

        if (FastUtils.checkNull(whiteListDto.getPhone())){
            return AjaxResult.error("手机号不能为空！");
        }
        WhiteList whiteList = whiteListService.getOne(new LambdaQueryWrapper<WhiteList>().eq(WhiteList::getPhone,whiteListDto.getPhone()).
                notIn(WhiteList::getId,whiteListDto.getId()).eq(WhiteList::getStatus,DataConstants.Number.ZERO));
        if (!FastUtils.checkNull(whiteList)){
            return AjaxResult.error("修改的手机号已存在！");
        }
        Integer result = whiteListService.updateByPrimaryKey(whiteListDto);
        if (result > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改白名单信息失败！");
    }


    /**
     * 删除白名单信息（逻辑删）
     *
     * @param whiteListDto
     * @return
     */
    @PreAuthorize("@ss.hasPermi('whiteList:list:delete')")
    @ApiOperation("删除白名单信息")
    @Log(title = "系统管理-白名单", businessType = BusinessType.DELETE)
    @ApiImplicitParam(name = "id", value = "数据id", dataType = "Integer", dataTypeClass = Integer.class)
    @DeleteMapping("deleteWhiteListInfo")
    public AjaxResult deleteWhiteListInfo(@RequestBody WhiteListDto whiteListDto) {
        boolean result = whiteListService.removeById(whiteListDto);
        if (result) {
            return AjaxResult.success();
        }
        return AjaxResult.error("白名单删除失败！");
    }

}
